<template>
  <a-card>

    <a-row class="row">
      <a-col :span="4" class="rowLabel">题目名称</a-col>
      <a-col :span="10">
        <a-input v-model:value="formData.questionName" :maxlength="20" show-count/>
      </a-col>
    </a-row>
    <a-row class="row">
      <a-col :span="4" class="rowLabel">分类标签</a-col>
      <a-col :span="10">
        <a-checkbox-group v-model:value="formData.questionTag" :options="questionTagOptions"/>
      </a-col>
    </a-row>
    <a-row class="row">
      <a-col :span="4" class="rowLabel">备注</a-col>
      <a-col :span="10">
        <a-textarea v-model:value="formData.bak" :maxlength="100" show-count/>
      </a-col>
    </a-row>
    <a-row class="row">
      <a-col :span="4" class="rowLabel">题目属性</a-col>
      <a-col :span="10">
        <a-switch :disabled="formData.occupyFlag!==0" :checked="formData.selectType===0" @click="switchChange('selectType')"/>
        <span>{{ formatQuestionInfo('selectType', formData.selectType) }}</span>
        <a-switch :disabled="formData.occupyFlag!==0" :checked="formData.requiredFlag===1" style="margin-left: 16px" @click="switchChange('requiredFlag')"/>
        <span>{{ formatQuestionInfo('requiredFlag', formData.requiredFlag) }}</span>
      </a-col>
    </a-row>

    <div class="draggableZ">

      <!--      <div v-for="option in formData.optionNameConcat"-->
      <!--           style="background-color: #00a0e9;margin-bottom: 12px">-->
      <!--        {{option}}-->
      <!--      </div>-->


      <Draggable :force-fallback="true" :list="formData.options"
                 animation="300" ghost-class="ghost" handle=".draggableIcon">
        <template #item="{ element,index }">
          <div v-if="element?.deleteFlag!==1" style="margin-bottom: 24px">
            <a-row class="row alignCenter">
              <a-col :span="4" class="rowLabel">
                <DragOutlined class="draggableIcon"/>
              </a-col>
              <a-col :span="16">
                <a-input v-model:value="element.optionName" :maxlength="50" placeholder="请输入选项名称" show-count/>
              </a-col>
              <a-col :span="2">
                <CloseOutlined v-if="formData.occupyFlag===0" style="margin-left: 8px;cursor: pointer" @click="removeOption(index)"/>
              </a-col>
            </a-row>

            <a-row class="row alignCenter">
              <a-col :span="4" class="rowLabel">选项属性</a-col>
              <a-col :span="10">
                成色等级
                <a-select v-model:value="element.grade" placeholder="成色" style="width: 80px">
                  <a-select-option :value="-1">N</a-select-option>
                  <a-select-option :value="1">A</a-select-option>
                  <a-select-option :value="2">B</a-select-option>
                  <a-select-option :value="3">C</a-select-option>
                  <a-select-option :value="4">D</a-select-option>
                  <a-select-option :value="0">S</a-select-option>
                </a-select>
                <a-switch :disabled="formData.occupyFlag!==0"
                          :checked="element.choosable===1" style="margin-left: 16px"
                          @click="choosableSwitchChange(index)"/>
                <span>{{ formatQuestionInfo('choosable', element.choosable) }}</span>
              </a-col>
            </a-row>
            <a-row v-if="element.choosable===0" class="row alignCenter">
              <a-col :span="4" class="rowLabel">
              </a-col>
              <a-col :span="16">
                <a-input v-model:value="element.reason" :maxlength="100"
                         placeholder="不可选理由(用于补充解释为何不回收)"
                         show-count/>
              </a-col>
            </a-row>
            <a-row class="row alignCenter">
              <a-col :span="4" class="rowLabel">
              </a-col>
              <a-col :span="16">
                <a-input v-model:value="element.bak" :maxlength="100" placeholder="请输入选项说明(用于补充解释选项名称)"
                         show-count/>
              </a-col>
            </a-row>
            <a-row class="row alignCenter">
              <a-col :span="4" class="rowLabel">
              </a-col>
              <a-col :span="16">

                <FileUpload
                    :defaultFileList="element.optionImg"
                    :folder="FILE_FOLDER_TYPE_ENUM.COMMON.value"
                    :maxUploadSize="3"
                    :multiple="true"
                    buttonText="点击上传图片"
                    list-type="picture-card"
                    @change="imgChange($event,index)"
                />

              </a-col>
            </a-row>
          </div>
        </template>
      </Draggable>

    </div>
    <div style="text-align: center;cursor: pointer" @click="addOption">
      <PlusOutlined/>
      添加选项
    </div>

    <div style="text-align: right">
      <a-button style="margin-right: 24px" @click="cancel">取消</a-button>
      <a-button type="primary" @click="save">保存</a-button>
    </div>

  </a-card>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import Draggable from 'vuedraggable';
import {FILE_FOLDER_TYPE_ENUM} from "/@/constants/support/file-const";
import FileUpload from "/@/components/support/file-upload/index.vue";
import {questionApi, formatQuestionInfo} from "./question-api";
import {message} from "ant-design-vue";
import _ from 'lodash';
import {smartSentry} from "/@/lib/smart-sentry";

import {useRoute, useRouter} from 'vue-router';

const route = useRoute();
const router = useRouter();
/**
 * options
 *     {
 *       bak: "1",
 *       choosable: 0, 0-不可选 1-可选 ,
 *       grade: 0, 等级价值
 *       optionImg: "string",
 *       optionName: "string",
 *       reason: "string",不可选理由 ,
 *       sort: 0
 *     }
 */

const formData = reactive({
  id: undefined,
  bak: undefined, // 备注
  questionName: undefined, // 题目名称
  occupyFlag: 0, // 是否全部可编辑  0 可以 1不可以
  questionTag: [], //  0.通用 1.iphone 2.ipad 3.安卓 多选逗号拼接
  requiredFlag: 1, // 是否必选 0-非必选 1-必选
  selectType: 0, // 是否单选 0-单选 1-多选
  options: [], // 选项
});
const questionTagOptions = [
  {label: '通用', value: '0'},
  {label: 'iPhone', value: '1'},
  {label: 'iPad', value: '2'},
  {label: '安卓手机', value: '3'},
]

onMounted(async () => {
  if (route.query?.questionId !== undefined) {
    try {
      const {data} = await questionApi.detail(route.query?.questionId);
      formData.id = JSON.parse(route.query?.isCopy) ? '' : data.id;
      formData.bak = data.bak;
      formData.questionName = data.questionName;
      formData.requiredFlag = data.requiredFlag;
      formData.occupyFlag = data.occupyFlag;
      formData.selectType = data.selectType;
      formData.questionTag = data.questionTag.split(',');
      formData.options = data.options.map(item => {
        item.optionImg = item.optionImg ? item.optionImg.split(',').map(imgItem => {
          const imgType = imgItem ? imgItem.split('_') : '';
          return {fileUrl: imgItem, fileType: imgType[imgType.length - 1]};
        }) : [];
        item.id = JSON.parse(route.query?.isCopy) ? '' : item.id;
        return item;
      });
      console.log(formData.options)
    } catch (error) {
      smartSentry.captureError(error);
    }
  }
})

function switchChange(attr) {
  formData[attr] = formData[attr] === 1 ? 0 : 1;
}

// 移除选项
function removeOption(index) {
  formData.options = formData.options.map((v, i) => {
    if (i == index) {
      v.deleteFlag = 1;
    }
    return v;
  });
}

// 选项可选switch状态改变
function choosableSwitchChange(index) {
  formData.options[index].choosable = formData.options[index].choosable === 1 ? 0 : 1;
}

function addOption() {
  formData.options.push({
    bak: '',
    choosable: 1,
    grade: -1,
    optionImg: [],
    optionName: '',
    reason: '',
    deleteFlag: 0
  })
}

// 图片改变
function imgChange(e, optionIndex) {
  formData.options[optionIndex].optionImg = e;
  console.log(e, optionIndex);
}

// 保存
async function save() {
  const formDataClone = _.cloneDeep(formData);
  if (!formDataClone.questionName) {
    return message.error('请输入题目名称');
  }
  if (!formDataClone.questionTag.length) {
    return message.error('请选择分类标签');
  }
  if (!formDataClone.options.length) {
    return message.error('请添加选项');
  }
  let optionVerify = false;
  let optionIndex = 0;
  formDataClone.options.forEach((item, index) => {
    if (!item.optionName) {
      message.error(`请输入第${index + 1}个选项名称`);
      optionVerify = true;
    }
    if (item.choosable !== 1 && !item.reason) {
      message.error(`请输入第${index + 1}个选项的不可选理由`);
      optionVerify = true;
    }
    if (item.deleteFlag !== 1) {
      item.sort = optionIndex++;
    }
    item.optionImg = item.optionImg.map(item => item.fileUrl).join(',');
  })
  if (optionVerify) {
    return;
  }
  formDataClone.questionTag = formDataClone.questionTag.join(',');

  try {
    if (formDataClone.id) {
      await questionApi.update(formDataClone);
    } else {
      await questionApi.add(formDataClone);
    }
    message.success(`${formDataClone.id ? '修改' : '添加'}成功`);
    cancel();
  } catch (error) {
    smartSentry.captureError(error);
  }
  console.log(formData.options)
}

// 取消
function cancel() {
  router.push('/evaluate/question/question-list');
}
</script>

<style lang="less" scoped>
.row {
  margin-bottom: 8px;

  .rowLabel {
    text-align: right;
    padding-right: 8px;
  }
}

.draggableZ {
  .draggableIcon {
    cursor: all-scroll;
  }

}

.alignCenter {
  display: flex;
  flex-direction: row;
  align-items: center;
}
</style>